package main

import (
	"sort"
)

func abs(v int) int {
	if v >= 0 {
		return v
	} else {
		return -v
	}
}

func threeSumClosest(nums []int, target int) int {
	sort.Ints(nums)
	size := len(nums)
	result := nums[0] + nums[1] + nums[2]
	for i := 0; i < size; i++ {
		j := i + 1
		k := size - 1
		for j < k {
			v := nums[i] + nums[j] + nums[k]
			if abs(target-v) < abs(target-result) {
				result = v
			}
			if v > target {
				k--
			} else if v < target {
				j++
			} else if v == target {
				return result
			}
		}
	}
	return result
}
